package logic

import (
	"context"
	"errors"
	"fmt"
	"shop/cache"
	"shop/model/mysql"
	"shop/pkg"

	"shop/internal/svc"
	"shop/shop"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *shop.LoginRequest) (*shop.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	var u mysql.User
	u.Mobile = in.Mobile
	if err = u.GetByMobile(); err != nil {
		logx.Errorf("查询不到此手机号码")
		return nil, errors.New("查询不到此手机号码")
	}
	if u.ID < 0 {
		u.Password = pkg.Md5(in.Password)
		if err = u.Create(); err != nil {
			logx.Errorf("注册失败")
			return nil, errors.New("注册失败")
		}
	}
	result, _ := cache.Rdb.Get(l.ctx, "SendSmsErr"+in.Mobile).Result()
	if result == "" {
		logx.Errorf("验证码失效")
		return nil, errors.New("验证码失效")
	}
	fmt.Println(u.Password, pkg.Md5(in.Password))
	if u.Password != pkg.Md5(in.Password) {
		logx.Errorf("密码错误")
		return nil, errors.New("密码错误")
	}

	return &shop.LoginResponse{
		Id: int64(u.ID),
	}, nil
}
